package cn.com.chec.en.controller.admin;

import java.io.BufferedWriter;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import cn.com.chec.en.util.ContactUtils;

@Controller
@RequestMapping({ "/admin/contact" })
public class ContactAdminController {
	protected static final Logger logger = Logger
			.getLogger(ContactAdminController.class);

	@RequestMapping({ "/showUpdate" })
	public ModelAndView showUpdate(ModelMap map) {
		map.putAll(ContactUtils.getContactMap());
		map.put("act", "update");
		return new ModelAndView("admin/contactInfo/contactManager", map);
	}

	@RequestMapping({ "/update" })
	public ModelAndView update(HttpServletRequest request,
			HttpServletResponse response, ModelMap map) throws Exception {
		String message = "";
		String filePath = ContactAdminController.class.getClassLoader()
				.getResource("cn/com/chec/en/conf/contact.properties")
				.getPath();
		if ((StringUtils.isNotBlank(filePath)) && (filePath.length() > 0)) {
			filePath = filePath.substring(1);
		}
		String telphone = request.getParameter("telphone");
		String email = request.getParameter("email");
		String address = request.getParameter("address");
		try {
			BufferedWriter bw = new BufferedWriter(new FileWriter(filePath));
			bw.write("telphone=" + telphone
					+ System.getProperty("line.separator"));
			bw.write("email=" + email + System.getProperty("line.separator"));
			bw.write("address=" + address
					+ System.getProperty("line.separator"));
			bw.close();
			message = "保存成功!";
		} catch (FileNotFoundException e) {
			message = "保存失败!";
			e.printStackTrace();
		} catch (IOException e) {
			message = "保存失败!";
			logger.error("[contact] save error !", e);
		}
		map.put("message", message);
		return new ModelAndView("admin/common/message", map);
	}
}